// service/TicketService.java
package main.java.com.cinema.service;

import main.java.com.cinema.model.Ticket;
import main.java.com.cinema.model.Showtime;
import main.java.com.cinema.model.SalesData;
import main.java.com.cinema.dao.TicketDAO;
import main.java.com.cinema.dao.ShowtimeDAO;
import main.java.com.cinema.util.Logger;


import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

public class TicketService {
    private TicketDAO ticketDAO = new TicketDAO();
    private ShowtimeDAO showtimeDAO = new ShowtimeDAO();
    
    public List<Ticket> listAllTickets() {
        return ticketDAO.findAll();
    }
    
    public Ticket findTicketById(String ticketId) {
        return ticketDAO.findById(ticketId);
    }
    
    public List<Ticket> findTicketsByShowtime(String showtimeId) {
        return ticketDAO.findByShowtimeId(showtimeId);
    }
    
    public boolean sellTicket(String operator, String showtimeId, int row, int seat) {
        Showtime showtime = showtimeDAO.findById(showtimeId);
        if (showtime == null) {
            return false;
        }
        
        // 检查座位是否已被占用
        if (showtime.isSeatOccupied(row, seat)) {
            return false;
        }
        
        // 检查电影是否即将开始（放映前1小时）
        if (showtime.getStartTime().isBefore(LocalDateTime.now().plusHours(1))) {
            return false;
        }
        
        // 创建电影票
        String ticketId = "T" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        Ticket ticket = new Ticket(ticketId, showtimeId, operator, row, seat, 
                                 LocalDateTime.now(), showtime.getPrice());
        
        // 更新座位状态
        showtime.setSeatOccupied(row, seat, true);
        showtimeDAO.update(showtime);
        
        boolean result = ticketDAO.save(ticket);
        if (result) {
            Logger.log("售票", "售出电影票: " + ticketId + " 场次: " + showtimeId + 
                      " 座位: " + row + "排" + seat + "座", operator);
        }
        return result;
    }
    
    public boolean refundTicket(String operator, String ticketId) {
        Ticket ticket = ticketDAO.findById(ticketId);
        if (ticket == null || ticket.isRefunded()) {
            return false;
        }
        
        Showtime showtime = showtimeDAO.findById(ticket.getShowtimeId());
        if (showtime == null) {
            return false;
        }
        
        // 检查是否在退票时间范围内（电影开始前1小时）
        if (showtime.getStartTime().isBefore(LocalDateTime.now().plusHours(1))) {
            return false;
        }
        
        // 标记票为已退
        ticket.setRefunded(true);
        ticket.setRefundTime(LocalDateTime.now());
        
        // 释放座位
        showtime.setSeatOccupied(ticket.getRow(), ticket.getSeat(), false);
        
        boolean result = ticketDAO.update(ticket) && showtimeDAO.update(showtime);
        if (result) {
            Logger.log("退票", "退电影票: " + ticketId, operator);
        }
        return result;
    }
    
    public boolean hasSoldTickets(String showtimeId) {
        List<Ticket> tickets = ticketDAO.findByShowtimeId(showtimeId);
        for (Ticket ticket : tickets) {
            if (!ticket.isRefunded()) {
                return true;
            }
        }
        return false;
    }
    
    // 统计销售数据
    public SalesData getDailySalesData(LocalDateTime date) {
        LocalDateTime start = date.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime end = date.withHour(23).withMinute(59).withSecond(59);
        return calculateSalesData(start, end);
    }
    
    public SalesData getWeeklySalesData(LocalDateTime startDate) {
        LocalDateTime end = startDate.plusDays(7);
        return calculateSalesData(startDate, end);
    }
    
    public SalesData getMonthlySalesData(LocalDateTime startDate) {
        LocalDateTime end = startDate.plusMonths(1);
        return calculateSalesData(startDate, end);
    }

    private SalesData calculateSalesData(LocalDateTime start, LocalDateTime end) {
        List<Ticket> tickets = ticketDAO.findAll();
        int totalSold = 0;
        double totalAmount = 0;
        int totalRefunded = 0;
        double refundAmount = 0;

        for (Ticket ticket : tickets) {
            if (!ticket.getPurchaseTime().isBefore(start) && !ticket.getPurchaseTime().isAfter(end)) {
                if (!ticket.isRefunded()) {
                    totalSold++;
                    totalAmount += ticket.getPrice();
                } else {
                    totalRefunded++;
                    refundAmount += ticket.getPrice();
                }
            }
        }

        return new SalesData(totalSold, totalAmount, totalRefunded, refundAmount);
    }
    

}
